package api

import "C"
import (
	"easyShop/model"
	"easyShop/services"
	"easyShop/utils"
	"encoding/json"
	"github.com/gin-gonic/gin"
)

type OrderController struct {
}

func (OrderController) Create(c *gin.Context) {
	// 获取UserInfo数据
	var userInfo model.User
	userInfoData, _ := c.Get("userInfo")
	marErr := utils.MapToStruct(userInfoData.(map[string]interface{}), &userInfo)

	if marErr != nil {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "获取用户数据失败",
			"data":    []string{},
		})
		return
	}
	// 获取Raw数据
	rawData, _ := c.GetRawData()
	var products []model.ProductData
	err := json.Unmarshal(rawData, &products)
	if err != nil {
		c.JSON(200, gin.H{
			"code":    500,
			"message": "获取数据失败",
			"data":    []string{},
		})
		return
	}

	for i := 0; i < len(products); i++ {
		if products[i].ProductId == 0 || products[i].Quantity == 0 {
			c.JSON(200, gin.H{
				"code":    500,
				"message": "参数错误",
				"data":    []string{},
			})
			return
		}
	}

	order, createErr := services.CreateOrder(userInfo.Id, products)
	if createErr != nil {
		c.JSON(200, gin.H{
			"code":    500,
			"message": createErr.Error(),
			"data":    []string{},
		})
		return
	}

	c.JSON(200, gin.H{
		"code":    200,
		"message": "success",
		"data":    map[string]interface{}{"order_id": order.Id, "total_price": order.TotalPrice},
	})
}
